package cn.tedu.csmall.order.webapi.service.impl;

import cn.tedu.csmall.cart.service.ICartService;
import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.order.dto.OrderAddDTO;
import cn.tedu.csmall.commons.pojo.order.model.Order;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.ResponseCode;

import cn.tedu.csmall.order.service.IOrderService;
import cn.tedu.csmall.order.webapi.mapper.OrderMapper;
import cn.tedu.csmall.stock.service.IStockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@DubboService
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    //添加@DubboReference 表示当前业务逻辑层要消费其他模块的服务了
    //注解后面声明的应该是Dubbo注册到Nacos其他模块声明的方法
    //业务逻辑层接口实现类会在Dubbo框架下自动获取
    @DubboReference
    private IStockService stockService;
    @DubboReference
    private ICartService cartService;


    @Override
    public void orderAdd(OrderAddDTO orderAddDTO) {

        //1.先去减少订单中商品库存数量（调用stock模块减少库存的方法）
        StockReduceCountDTO countDTO = new StockReduceCountDTO();
        countDTO.setCommodityCode(orderAddDTO.getCommodityCode());
        countDTO.setReduceCount(orderAddDTO.getCount());

        stockService.reduceCommodityCount(countDTO);
        //2.从购物车中减少用户勾选的商品（掉用cart模块删除购物车商品的方法）
        cartService.deleteUserCart(orderAddDTO.getUserId(),orderAddDTO.getCommodityCode());


       if (Math.random()<0.5){
           throw new CoolSharkServiceException(
                   ResponseCode.INTERNAL_SERVER_ERROR,"发生随机异常");
       }

        //3.新增订单信息
        Order order = new Order();
        BeanUtils.copyProperties(orderAddDTO,order);
        int rows = orderMapper.insertOrder(order);
        if (rows != 1) {
            String message = "新增失败";
            log.debug(message);
            throw new CoolSharkServiceException(ResponseCode.FORBIDDEN,message);
        }
        log.info("新增订单信息为{}",order);
    }


}
